package com.msun.auth.utils;

import java.util.Random;
import java.util.UUID;

public final class RandUtils {

    private static final Random RAND = new Random();

    public static Integer getRandNum(int max, int... skip) {
        RAND.setSeed(UUID.randomUUID().getLeastSignificantBits());
        int i = RAND.nextInt(max);
        int len = skip.length;
        if (len > 0) {
            for (int j = 0; j < len; j++) {
                if (i == skip[j]) {
                    return getRandNum(max, skip);
                }
            }
        }
        return i;
    }

    public static String getCode(int passLength, int type) {
        StringBuilder buffer = null;
        StringBuilder sb = new StringBuilder();
        switch (type) {
            case 0:
                buffer = new StringBuilder("0123456789");
                break;
            case 1:
                buffer = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
                break;
            case 2:
                buffer = new StringBuilder("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
                break;
            case 3:
                buffer = new StringBuilder(
                        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
                break;
            case 4:
                buffer = new StringBuilder(
                        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
                sb.append(buffer.charAt(getRandNum(buffer.length() - 10)));
                passLength -= 1;
                break;
            case 5:
                String s = UUID.randomUUID().toString();
                sb.append(s, 0, 8)
                        .append(s, 9, 13)
                        .append(s, 14, 18)
                        .append(s, 19, 23)
                        .append(s.substring(24));
        }

        if (type != 5) {
            assert buffer != null;
            int range = buffer.length();
            for (int i = 0; i < passLength; ++i) {
                sb.append(buffer.charAt(getRandNum(range)));
            }
        }
        return sb.toString();
    }

    public static int[] getSequence(int no) {
        int[] sequence = new int[no];
        for (int i = 0; i < no; i++) {
            sequence[i] = i;
        }
        for (int i = 0; i < no; i++) {
            int p = getRandNum(no);
            int tmp = sequence[i];
            sequence[i] = sequence[p];
            sequence[p] = tmp;
        }
        return sequence;
    }
}
